package com.chelun.support.clmutiplyfragment;

import android.content.Context;
import android.graphics.Rect;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;

import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created on 15/9/16.
 *
 * @author cxd
 */
public class ClMultiChelunPtrRefresh extends PtrFrameLayout {

    private float mLastX, mLastY;

    public ClMultiChelunPtrRefresh(Context context) {
        super(context);
        init(context);
    }

    public ClMultiChelunPtrRefresh(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ClMultiChelunPtrRefresh(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        ClMultiPtrDefaultHeader header = new ClMultiPtrDefaultHeader(context);
        setHeaderView(header);
        addPtrUIHandler(header);
        setLoadingMinTime(0);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent e) {

        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastX = e.getX();
                mLastY = e.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (Math.abs(e.getX() - mLastX) > Math.abs(e.getY() - mLastY)) {
                    if (isInIgnoredView(this, e.getX(), e.getY())) {
                        return dispatchTouchEventSupper(e);
                    }
                }
                mLastX = e.getX();
                mLastY = e.getY();

        }
        return super.dispatchTouchEvent(e);
    }

    private boolean isInIgnoredView(ViewGroup viewGroup, float x, float y) {
        int cc = viewGroup.getChildCount();
        for (int i = 0; i < cc; ++i) {
            View c = viewGroup.getChildAt(i);
            Rect rect = new Rect();
            c.getHitRect(rect);
            boolean isHit = rect.contains((int) x, (int) y);
            if (isHit) {
                if (c instanceof HorizontalScrollView) {
                    return true;
                } else if (c instanceof ViewPager) {
                    return true;
                } else if (c instanceof ViewGroup) {
                    boolean ret = isInIgnoredView((ViewGroup) c, x, y);
                    if (ret) return true;
                }
            }
        }
        return false;
    }
}
